package com.yunyang.jczd.facade.fileexport.service.impl;

import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunyang.jczd.base.account.feign.IAccountFacade;
import com.yunyang.jczd.base.account.vo.AccountInfoVO;
import com.yunyang.jczd.base.file.fileexport.dto.JczdExportRecordDTO;
import com.yunyang.jczd.base.file.fileexport.dto.SearchJczdExportRecordDTO;
import com.yunyang.jczd.business.convert.PageConvert;
import com.yunyang.jczd.business.response.PageResult;
import com.yunyang.jczd.business.web.current.RequestContext;
import com.yunyang.jczd.enums.ExportFileTypeEnum;
import com.yunyang.jczd.enums.ExportStateEnum;
import com.yunyang.jczd.enums.ExportTypeEnum;
import com.yunyang.jczd.facade.fileexport.entity.JczdExportRecord;
import com.yunyang.jczd.facade.fileexport.mapper.JczdExportRecordMapper;
import com.yunyang.jczd.facade.fileexport.service.IJczdExportRecordService;
import com.yunyang.jczd.foundation.core.common.helpers.BeanHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;

/**
 * <p>
 * 导出记录表 服务实现类
 * </p>
 *
 * @author author
 * @since 2020-11-11
 */
@Slf4j
@Service
public class JczdExportRecordServiceImpl extends ServiceImpl<JczdExportRecordMapper, JczdExportRecord> implements IJczdExportRecordService {

    @Autowired
    private IAccountFacade accountInfoMapper;

    @Value("${file.upload.path:/dev/fileStore/}")
    private String fileUploadPath;

    @Override
    public PageResult<JczdExportRecordDTO> pageJczdExportRecord(SearchJczdExportRecordDTO param) {
        QueryWrapper<JczdExportRecord> qw = new QueryWrapper<>();
        if (!StringUtils.isEmpty(param.getExporterName())){
            qw.like("exporter_name",param.getExporterName());
        }
        if (param.getStartTime() != null && param.getEndTime() != null){
            qw.between("export_time",param.getStartTime(),param.getEndTime());
        }
        qw.eq("exporter_id",param.getExportId()).eq("export_type",param.getExportType()).
                orderByDesc("export_time");
        IPage page = new Page();
        page.setCurrent(param.getPage());
        page.setSize(param.getSize());
        IPage jczdExportRecordIPage = this.page(page,qw);
        PageResult<JczdExportRecordDTO> jczdExportRecordDTOPageResult = PageConvert.convert(jczdExportRecordIPage,JczdExportRecordDTO.class);
        return jczdExportRecordDTOPageResult;
    }

    @Override
    public boolean updateExportState(Long id, Integer state) {
        LambdaUpdateWrapper<JczdExportRecord> qw = new LambdaUpdateWrapper<>();
        qw.set(JczdExportRecord::getExportState,state).eq(JczdExportRecord::getId,id);
        return this.update(qw);

    }


    @Override
    public JczdExportRecordDTO saveExport(Integer fileType, Integer exportType) {
        ExportFileTypeEnum exportFileTypeEnum = ExportFileTypeEnum.getByCode(fileType);
        if (Objects.isNull(exportFileTypeEnum)) {
            log.error("不支持的文件类型,fileType:{}", fileType);
            return null;
        }
        ExportTypeEnum exportTypeEnum = ExportTypeEnum.getByCode(exportType);
        if (Objects.isNull(exportTypeEnum)) {
            log.error("不支持的导出类型,exportType:{}", exportType);
            return null;
        }
        String fileName = getFileName(exportFileTypeEnum, exportTypeEnum);
        String filePath = getExcelFilePath(fileName);
        JczdExportRecord param = new JczdExportRecord();
        param.setExporterId(RequestContext.getAccountId());
        param.setExportPath(filePath);
        param.setFileType(fileType);
        param.setExportType(exportType);
        param.setFileName(fileName);
        param.setExportState(ExportStateEnum.ExportING.getCode());
        param.setExportTime(LocalDateTime.now());
        param.setExporterName(getExportName(param.getExporterId()));
        boolean result = this.save(param);
        if (result) return BeanHelper.map(JczdExportRecordDTO.class, param);
        return null;
    }


    public String getExportName(Long accountId) {
        AccountInfoVO account = accountInfoMapper.getById(accountId).getData();
        if (Objects.isNull(account)) return null;
        return account.getUserName();
    }

    public String getFileName(ExportFileTypeEnum exportFileTypeEnum,ExportTypeEnum exportTypeEnum) {
        String fileName = null;
        switch (exportFileTypeEnum) {
            case EXCEl:
                fileName = generateExcelFileName(exportTypeEnum);
                break;
            case PDF:
                fileName = generatePdfFileName(exportTypeEnum);
                break;
            case CSV:
                fileName = generateCsvFileName(exportTypeEnum);
                break;
        }
        return fileName;
    }


    public String getExcelFilePath(String fileName) {
        return getFilePath("images/",fileName);
    }

    public String getFilePath(String dir, String fileName) {
        return fileUploadPath + dir + fileName;
    }

    /**
     * 获取excel文件名
     **/
    public  String generateExcelFileName(ExportTypeEnum typeEnum) {
        return typeEnum.getDesc() + "_" + new Date().getTime() + ExcelTypeEnum.XLSX.getValue();
    }
    /**
     * 获取csv文件名
     **/
    public  String generateCsvFileName(ExportTypeEnum typeEnum) {
        return typeEnum.name().toLowerCase() + "_" + new Date().getTime() + ".csv";
    }
    /**
     * 获取pdf文件名
     **/
    public  String generatePdfFileName(ExportTypeEnum typeEnum) {
        return typeEnum.name().toLowerCase() + "_" + new Date().getTime() + ".pdf";
    }
}
